#include "Picture.h"
#include <string>
static uint32_t displaytime;
void settime(uint32_t time)
{
  displaytime=time;
  printf("%d",displaytime);
}
// creat a dynamic pad for decodebin2
void on_pad_added1 (GstElement *element,GstPad *pad,gpointer data)
{
  GstPad *sinkpad1;
  GstElement *convert1 = (GstElement *) data;
  g_print ("Dynamic pad created, linking demuxer/decoder\n");
  sinkpad1 = gst_element_get_static_pad (convert1, "sink");
  gst_pad_link (pad, sinkpad1);
  gst_object_unref (sinkpad1);
}


//Message processing function

gboolean bus_call1(GstBus *bus,GstMessage *msg,gpointer data)
{


  GMainLoop *loop = (GMainLoop *) data;
    switch (GST_MESSAGE_TYPE(msg))
    {
      case GST_MESSAGE_EOS:
      { 
        g_print("End of stream\n");
        sleep(displaytime);
        g_main_loop_quit(loop);
        break;
      }
      case GST_MESSAGE_ERROR:
      {
        gchar *debug;
        GError *error;
        gst_message_parse_error(msg,&error,&debug);
        g_free(debug);
        g_printerr("ERROR:%s\n",error->message);
        g_error_free(error);
        g_main_loop_quit(loop);
        break;
      }
      default:
        break;
    }
  return TRUE;
}


Picture::Picture(std::string l, int w,int h)
{

  picture_location=l;
  picture_width=w;
  picture_height=h;
  loop = g_main_loop_new(NULL,FALSE);    //create main loop 
  pipeline = gst_pipeline_new("picture-player");
  source = gst_element_factory_make("filesrc","file-source");
  decoder = gst_element_factory_make("jpegdec","decoder");
  sink = gst_element_factory_make("autovideosink","video-output");
                              //  create elements we need 
  bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));                     //create a bus 
  const char *picture_location_t=picture_location.c_str();
  g_object_set(G_OBJECT(source),"location",picture_location_t,NULL);        //set the properties of elements

}






int Picture::picture_display()
{      
  if(!pipeline||!source||!decoder||!sink)
  {
    g_printerr("One element could not be created.Exiting.\n");
    return -1;
  }
//add a bus to the pipeline
  gst_bus_add_watch(bus,bus_call1,loop);
  gst_object_unref(bus);    
// add the elements to the pipeline                                              
  gst_bin_add_many(GST_BIN(pipeline),source,decoder,sink,NULL);
//link all elements
  gst_element_link_many(source,decoder,sink);
  //gst_element_link_many(convert,videoscale,NULL);
  //g_signal_connect (decoder, "pad-added", G_CALLBACK (on_pad_added), convert);

//start playing
  gst_element_set_state(pipeline,GST_STATE_PLAYING);
  g_print("Running\n");
  g_main_loop_run(loop);
  
  g_print("Returned,stopping playback\n");
//end
  gst_element_set_state(pipeline,GST_STATE_NULL);
  gst_object_unref(GST_OBJECT(pipeline));
  return 0;  
}


